package com.astrob.view;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.DashPathEffect;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PathEffect;
import android.graphics.Point;
import android.graphics.drawable.BitmapDrawable;
import android.os.SystemClock;

import com.astrob.model.LonLat;
import com.astrob.naviframe.Start;
import com.astrob.nhcmap.R;
import com.astrob.util.SysUtils;
import com.astrob.util.Utils;
import com.nhc.database.dbmodel.TrackPoint;
import com.nhc.database.dbmodel.WayTrail;
import com.nhc.database.manager.DBDataCenter;

import org.mapsforge.core.graphics.Style;
import org.mapsforge.core.util.MercatorProjection;
import org.mapsforge.map.android.graphics.AndroidGraphicFactory;
import org.mapsforge.map.model.DisplayModel;
import org.osmdroid.util.BoundingBox;
import org.osmdroid.util.GeoPoint;
import org.osmdroid.views.MapView;
import org.osmdroid.views.Projection;
import org.osmdroid.views.overlay.Polyline;

import java.util.ArrayList;
import java.util.List;

public class TrackShow {

    private static TrackShow instance = new TrackShow();

    public static TrackShow getInstance() {
        return instance;
    }

    public PathEffect getPathEffect(int pathstyle) {
        PathEffect pathEffect = null;
        switch (pathstyle) {
            default:
            case 0://实线
                pathEffect = new DashPathEffect(new float[]{5, 0}, 0);
                break;
            case 1://虚线1
                pathEffect = new DashPathEffect(new float[]{5, 5, 5, 5}, 1);
                break;
            case 2://虚线2
                pathEffect = new DashPathEffect(new float[]{10, 10}, 1);
                break;
            case 3://虚线2
                pathEffect = new DashPathEffect(new float[]{20, 10, 5, 10}, 0);
                break;
            case 4://虚线2
                pathEffect = new DashPathEffect(new float[]{20, 10}, 0);
                break;
            case 5://虚线2
                pathEffect = new DashPathEffect(new float[]{12, 8, 6, 4}, 0);
                break;
        }
        return pathEffect;
    }


    public void drawWayTrailAll(Context context, Canvas canvas, float ws, MapViewS mapView, WayTrail wtOne) {

        Paint paint = new Paint();
        paint.reset();
        paint.setStyle(Paint.Style.STROKE);
        if (SysUtils.getInstance().is240x320) {
            paint.setStrokeWidth(6);
        } else {
            paint.setStrokeWidth(8);
        }
        paint.setStrokeJoin(Paint.Join.ROUND);
        paint.setAntiAlias(true);

        ArrayList<WayTrail> wayTrailList = DBDataCenter.getInstance().getWaytrailListByOrder(0);
        boolean showIcon = false;
        if (wtOne != null) {
            showIcon = true;
        }

//由当前比例尺确定 返回 GeoHash的精度-字符串的有效长度 left
        int level = Start.getInstance().MapKit().getScaleLevel();
        int glen = Start.getInstance().MapKit().getGeoHashLevel(level);

        for (WayTrail wt : wayTrailList) {
            if (DBDataCenter.getInstance().wayTrailNavi != null && DBDataCenter.getInstance().wayTrailNavi.getId() == wt.getId()) {
                continue;//导航航迹最后画，导航航迹也可能不在数据库里，如返程导航
            }

            if (wtOne != null && wtOne.getId() != wt.getId()) {
                continue;
            }

            if (wtOne == null && !wt.getIsshow()) {
                continue;
            }

            if (wt.trackPointList == null || wt.trackPointList.size() < 1) {
                wt.trackPointList = DBDataCenter.getInstance().getTrackPointByWayTrail(wt, null);
            }

            paint.setColor(wt.getColor());
            int pathstyle = wt.getPathstyle();
            PathEffect pathEffect = TrackShow.getInstance().getPathEffect(pathstyle);
            paint.setPathEffect(pathEffect);

            List<GeoPoint> points = wt.getGPlist(glen, true);
            drawWayTrailByPoints(context, canvas, ws, mapView, points, paint, showIcon);
        }

        //导航的航迹在最上面
        if (DBDataCenter.getInstance().wayTrailNavi != null) {
            WayTrail wt = DBDataCenter.getInstance().wayTrailNavi;
            if (wt.trackPointList == null) {
                wt.trackPointList = DBDataCenter.getInstance().getTrackPointByWayTrail(wt, null);
            }

            if (SysUtils.getInstance().is240x320) {
                paint.setStrokeWidth(6);
            } else {
                paint.setStrokeWidth(8);
            }
//            paint.setColor(wt.getColor());
            paint.setColor(Color.parseColor("#AA47B1F9"));//导航
            int pathstyle = wt.getPathstyle();
            PathEffect pathEffect = TrackShow.getInstance().getPathEffect(pathstyle);
            paint.setPathEffect(pathEffect);

            List<GeoPoint> points = wt.getGPlist(glen, true);
            drawWayTrailByPoints(context, canvas, ws, mapView, points, paint, true);
        }

    }


    public void drawWayTrailByPoints(Context context, Canvas canvas, float ws, MapViewS mapView, List<GeoPoint> points, Paint paint, boolean showIcon) {
        if (points == null || points.size() < 2) {
            return;
        }

        double[] regions = mapView.getMapRegion();
        if (regions != null && regions.length == 4) {
            _maxLon = regions[0];
            _maxLat = regions[1];
            _minLon = regions[2];
            _minLat = regions[3];
        } else {
            return;
        }
        int w = mapView._mapWidth;
        int h = mapView._mapHeight;

        int level = Start.getInstance().MapKit().getScaleLevel();
        int glen = Start.getInstance().MapKit().getGeoHashLevel(level);


        double range = 0.01;
        if (glen <= 7) {
            range = 1;
        } else if (glen <= 5) {
            range = 10;
        }
        double maxLon = regions[0] + range;
        double maxLat = regions[1] + range;
        double minLon = regions[2] - range;
        double minLat = regions[3] - range;

        long A = SystemClock.uptimeMillis();

        if (paint == null) {
            paint = new Paint();
            paint.setStyle(Paint.Style.STROKE);
            if (SysUtils.getInstance().is240x320) {
                paint.setStrokeWidth(6);
            } else {
                paint.setStrokeWidth(8);
            }
            paint.setAntiAlias(true);
        }
        Point ff0 = null;
        Point fflast = null;
        Point ffE = null;
        ArrayList<Point> pointlist = new ArrayList<Point>();
        int size = points.size();
        if (size > 0) {
            for (int i = 0; i < size; i++) {
                GeoPoint pt = points.get(i);
                int d = 10;
                if (glen > 4 || size > 1000) {
                    if (pt.getLongitude() > maxLon || pt.getLongitude() < minLon
                            || pt.getLatitude() > maxLat || pt.getLatitude() < minLat) {
                        continue;
                    }
                    d = 2;
                }
                Point ff = Start.getInstance().MapKit().LL2XY(new LonLat(pt.getLongitude(), pt.getLatitude()));//这是费时的，所以TME的drawPath需要截取

                if (size > 1000) {
                    if (ff.x < -w || ff.x > d * w || ff.y < -h || ff.y > d * h) {
                        continue;
                    }
                    if (fflast != null) {
                        if (Math.abs(fflast.x - ff.x) + Math.abs(fflast.y - ff.y) <= 1)
                            continue;
                    }
                }

                pointlist.add(ff);
                fflast = ff;
            }

            GeoPoint pt0 = points.get(0);
            ff0 = Start.getInstance().MapKit().LL2XY(new LonLat(pt0.getLongitude(), pt0.getLatitude()));//这是费时的，所以TME的drawPath需要截取

            GeoPoint ptE = points.get(size - 1);
            ffE = Start.getInstance().MapKit().LL2XY(new LonLat(ptE.getLongitude(), ptE.getLatitude()));//这是费时的，所以TME的drawPath需要截取
        }

        Path path = new Path();
        for (int i = 0; i < pointlist.size(); i++) {
            Point ff = pointlist.get(i);
            if (i == 0) {
                path.moveTo(ff.x * ws, ff.y * ws);
            } else {
                path.lineTo(ff.x * ws, ff.y * ws);
            }
        }
        canvas.drawPath(path, paint);

        long C = SystemClock.uptimeMillis() - A;//0ms

        if (!showIcon) {
            return;
        }

        Bitmap bmS = ((BitmapDrawable) context.getResources().getDrawable(
                R.drawable.map_marker3)).getBitmap();
        Bitmap bmD = ((BitmapDrawable) context.getResources().getDrawable(
                R.drawable.destination)).getBitmap();

        if (ff0 != null) {
            int x = (int) (ff0.x * ws - bmS.getWidth() / 2);
            int y = (int) (ff0.y * ws - bmS.getHeight());
            canvas.drawBitmap(bmS, x, y, null);
        }

        if (ffE != null) {
            int x = (int) (ffE.x * ws - bmD.getWidth() / 2);
            int y = (int) (ffE.y * ws - bmD.getHeight() / 2);
            canvas.drawBitmap(bmD, x, y, null);
        }

    }


    public void drawWayTrail2(Context context, Canvas canvas, final MapView mapView, WayTrail wtOne, boolean isgcj02) {

        ArrayList<WayTrail> wayTrailList = DBDataCenter.getInstance().getWaytrailListByOrder(0);
        Point ff0 = null;
        Point ffE = null;
        int size = 0;

        int glen = mapView.getZoomLevel(false);

        for (WayTrail wt : wayTrailList) {
            if (DBDataCenter.getInstance().wayTrailNavi != null && DBDataCenter.getInstance().wayTrailNavi.getId() == wt.getId()) {
                continue;//导航航迹最后画，导航航迹也可能不在数据库里，如返程导航
            }

            if (wtOne != null && wtOne.getId() != wt.getId()) {
                continue;
            }

            if (wtOne == null && !wt.getIsshow()) {
                continue;
            }

            if (wt.trackPointList == null) {
                wt.trackPointList = DBDataCenter.getInstance().getTrackPointByWayTrail(wt, null);
            }

            List<GeoPoint> points = wt.getGPlist(glen, isgcj02);

            Polyline routeline = new Polyline();
            if (SysUtils.getInstance().is240x320) {
                routeline.setWidth(4);
            } else {
                routeline.setWidth(8);
            }

            routeline.setPoints(points);

            routeline.setColor(wt.getColor());
            int pathstyle = wt.getPathstyle();
            PathEffect pathEffect = TrackShow.getInstance().getPathEffect(pathstyle);
            routeline.getPaint().setPathEffect(pathEffect);
            routeline.draw(canvas, mapView, false);

            size = points.size();
            if (wtOne != null && size > 0) {
                ff0 = LL2XYByOnline(new LonLat(points.get(0).getLongitude(), points.get(0).getLatitude()), mapView.getProjection());
                ffE = LL2XYByOnline(new LonLat(points.get(size - 1).getLongitude(), points.get(size - 1).getLatitude()), mapView.getProjection());
            }
        }

        //导航的航迹在最上面
        if (DBDataCenter.getInstance().wayTrailNavi != null) {
            WayTrail wt = DBDataCenter.getInstance().wayTrailNavi;
            if (wt.trackPointList == null) {
                wt.trackPointList = DBDataCenter.getInstance().getTrackPointByWayTrail(wt, null);
            }

            List<GeoPoint> points = wt.getGPlist(glen, isgcj02);

            Polyline routeline = new Polyline();
            if (SysUtils.getInstance().is240x320) {
                routeline.setWidth(6);
            } else {
                routeline.setWidth(13);
            }
            routeline.setPoints(points);

            routeline.setColor(Color.parseColor("#AA47B1F9"));
//            routeline.setColor(wt.getColor());
            int pathstyle = wt.getPathstyle();
            PathEffect pathEffect = TrackShow.getInstance().getPathEffect(pathstyle);
            routeline.getPaint().setPathEffect(pathEffect);
            routeline.draw(canvas, mapView, false);

            size = points.size();
            if (size > 0) {
                ff0 = LL2XYByOnline(new LonLat(points.get(0).getLongitude(), points.get(0).getLatitude()), mapView.getProjection());
                ffE = LL2XYByOnline(new LonLat(points.get(size - 1).getLongitude(), points.get(size - 1).getLatitude()), mapView.getProjection());
            }
        }

        if (ff0 != null) {
            Bitmap bmS = ((BitmapDrawable) context.getResources().getDrawable(
                    R.drawable.map_marker3)).getBitmap();

            int x = (int) (ff0.x - bmS.getWidth() / 2);
            int y = (int) (ff0.y - bmS.getHeight());
            canvas.drawBitmap(bmS, x, y, null);
        }

        if (ffE != null) {
            Bitmap bmD = ((BitmapDrawable) context.getResources().getDrawable(
                    R.drawable.destination)).getBitmap();

            int x = (int) (ffE.x - bmD.getWidth() / 2);
            int y = (int) (ffE.y - bmD.getHeight() / 2);
            canvas.drawBitmap(bmD, x, y, null);
        }

    }

    //OSM引擎
    Point LL2XYByOnline(LonLat ll, Projection pj) {
        Point B = new Point();
        if (pj != null) {
            Point mMapCoordsProjected = new Point();
            pj.toProjectedPixels(ll.GetLat(), ll.GetLon(), mMapCoordsProjected);
            pj.toPixelsFromProjected(mMapCoordsProjected, B);
        }
        return B;
    }

    public void drawWayTrail3(Context context, Canvas canvas, org.mapsforge.core.model.BoundingBox bb, byte zoomLevel, org.mapsforge.core.model.Point topLeftPoint, DisplayModel displayModel, WayTrail wtOne) {

        Paint paint = new Paint();
        paint.reset();
        paint.setStyle(Paint.Style.STROKE);

        if (SysUtils.getInstance().is240x320) {
            paint.setStrokeWidth(6);
        } else {
            paint.setStrokeWidth(8);
        }
        paint.setStrokeJoin(Paint.Join.ROUND);
        paint.setAntiAlias(true);

        int glen = zoomLevel;

        ArrayList<WayTrail> wayTrailList = DBDataCenter.getInstance().getWaytrailListByOrder(0);
        Point ff0 = null;
        Point ffE = null;
        int size = 0;
        long mapSize = MercatorProjection.getMapSize(zoomLevel, displayModel.getTileSize());

        for (WayTrail wt : wayTrailList) {
            if (DBDataCenter.getInstance().wayTrailNavi != null && DBDataCenter.getInstance().wayTrailNavi.getId() == wt.getId()) {
                continue;//导航航迹最后画，导航航迹也可能不在数据库里，如返程导航
            }

            if (wtOne != null && wtOne.getId() != wt.getId()) {
                continue;
            }

            if (wtOne == null && !wt.getIsshow()) {
                continue;
            }

            if (wt.trackPointList == null) {
                wt.trackPointList = DBDataCenter.getInstance().getTrackPointByWayTrail(wt, null);
            }

            List<GeoPoint> points = wt.getGPlist(glen, false);

            android.graphics.Path path = new android.graphics.Path();
            for (int i = 0; i < points.size(); i++) {
                GeoPoint gp = points.get(i);

                float x = (float) (MercatorProjection.longitudeToPixelX(gp.getLongitude(), mapSize) - topLeftPoint.x);
                float y = (float) (MercatorProjection.latitudeToPixelY(gp.getLatitude(), mapSize) - topLeftPoint.y);

                if (i == 0) {
                    path.moveTo(x, y);
                } else {
                    path.lineTo(x, y);
                }
            }

            paint.setColor(wt.getColor());
            int pathstyle = wt.getPathstyle();
            PathEffect pathEffect = TrackShow.getInstance().getPathEffect(pathstyle);
            paint.setPathEffect(pathEffect);
            canvas.drawPath(path, paint);

            size = points.size();
            if (wtOne != null && size > 0) {
                ff0 = new Point();
                ffE = new Point();
                ff0.x = (int) (MercatorProjection.longitudeToPixelX(points.get(0).getLongitude(), mapSize) - topLeftPoint.x);
                ff0.y = (int) (MercatorProjection.latitudeToPixelY(points.get(0).getLatitude(), mapSize) - topLeftPoint.y);
                ffE.x = (int) (MercatorProjection.longitudeToPixelX(points.get(size - 1).getLongitude(), mapSize) - topLeftPoint.x);
                ffE.y = (int) (MercatorProjection.latitudeToPixelY(points.get(size - 1).getLatitude(), mapSize) - topLeftPoint.y);
            }
        }

        //导航的航迹在最上面
        if (DBDataCenter.getInstance().wayTrailNavi != null) {
            android.graphics.Path path = new android.graphics.Path();
            WayTrail wt = DBDataCenter.getInstance().wayTrailNavi;
            if (wt.trackPointList == null) {
                wt.trackPointList = DBDataCenter.getInstance().getTrackPointByWayTrail(wt, null);
            }
            List<GeoPoint> points = wt.getGPlist(glen, false);
            for (int i = 0; i < points.size(); i++) {
                GeoPoint gp = points.get(i);

                float x = (float) (MercatorProjection.longitudeToPixelX(gp.getLongitude(), mapSize) - topLeftPoint.x);
                float y = (float) (MercatorProjection.latitudeToPixelY(gp.getLatitude(), mapSize) - topLeftPoint.y);

                if (i == 0) {
                    path.moveTo(x, y);
                } else {
                    path.lineTo(x, y);
                }
            }

            if (SysUtils.getInstance().is240x320) {
                paint.setStrokeWidth(6);
            } else {
                paint.setStrokeWidth(8);
            }
            paint.setColor(Color.parseColor("#AA47B1F9"));
            int pathstyle = wt.getPathstyle();
            PathEffect pathEffect = TrackShow.getInstance().getPathEffect(pathstyle);
            paint.setPathEffect(pathEffect);
            canvas.drawPath(path, paint);

            size = points.size();
            if (size > 0) {
                ff0 = new Point();
                ffE = new Point();
                if (wt.isReverse) {
                    ffE.x = (int) (MercatorProjection.longitudeToPixelX(points.get(0).getLongitude(), mapSize) - topLeftPoint.x);
                    ffE.y = (int) (MercatorProjection.latitudeToPixelY(points.get(0).getLatitude(), mapSize) - topLeftPoint.y);
                    ff0.x = (int) (MercatorProjection.longitudeToPixelX(points.get(size - 1).getLongitude(), mapSize) - topLeftPoint.x);
                    ff0.y = (int) (MercatorProjection.latitudeToPixelY(points.get(size - 1).getLatitude(), mapSize) - topLeftPoint.y);
                } else {
                    ff0.x = (int) (MercatorProjection.longitudeToPixelX(points.get(0).getLongitude(), mapSize) - topLeftPoint.x);
                    ff0.y = (int) (MercatorProjection.latitudeToPixelY(points.get(0).getLatitude(), mapSize) - topLeftPoint.y);
                    ffE.x = (int) (MercatorProjection.longitudeToPixelX(points.get(size - 1).getLongitude(), mapSize) - topLeftPoint.x);
                    ffE.y = (int) (MercatorProjection.latitudeToPixelY(points.get(size - 1).getLatitude(), mapSize) - topLeftPoint.y);
                }

            }
        }

        if (ff0 != null) {
            Bitmap bmS = ((BitmapDrawable) context.getResources().getDrawable(
                    R.drawable.map_marker3)).getBitmap();

            int x = (int) (ff0.x - bmS.getWidth() / 2);
            int y = (int) (ff0.y - bmS.getHeight());
            canvas.drawBitmap(bmS, x, y, null);
        }

        if (ffE != null) {
            Bitmap bmD = ((BitmapDrawable) context.getResources().getDrawable(
                    R.drawable.destination)).getBitmap();

            int x = (int) (ffE.x - bmD.getWidth() / 2);
            int y = (int) (ffE.y - bmD.getHeight() / 2);
            canvas.drawBitmap(bmD, x, y, null);
        }

    }


    //=================历史不用===============================

    double _maxLon, _maxLat, _minLon, _minLat;

    //实时航迹点，变化的实时计算需要显示的航迹
    //如果都放在内存里，会占用大内存，先即时查询
    //如果wtOne不为null则只画wtOne，忽略是否显示的属性
    public void drawWayTrail(Context context, Canvas canvas, float ws, MapViewS mapView, WayTrail wtOne) {
        double[] regions = mapView.getMapRegion();
        if (regions != null && regions.length == 4) {
            _maxLon = regions[0];
            _maxLat = regions[1];
            _minLon = regions[2];
            _minLat = regions[3];
        } else {
            return;
        }
        int w = mapView._mapWidth;
        int h = mapView._mapHeight;

        long Z = SystemClock.uptimeMillis();

        //显示所有航迹 --最新的航迹最后画（包括当前航迹）
        ArrayList<WayTrail> wayTrailList = DBDataCenter.getInstance().getWaytrailListByOrder(0);

        Paint paint = new Paint();
        paint.setStyle(Paint.Style.STROKE);
        paint.setStrokeWidth(8);
        paint.setAntiAlias(true);

        for (WayTrail wt : wayTrailList) {
            if (wtOne != null && wtOne.getId() != wt.getId()) {
                continue;
            }

            if (wtOne == null && !wt.getIsshow()) {
                continue;
            }
            long A = SystemClock.uptimeMillis();
            // 每次查询数据库慢，还是放内存里试试
            ArrayList<TrackPoint> trackPointList = getTrackPointByWayTrail(wt, regions, w);
            if (trackPointList == null) {
                continue;
            }
//            ArrayList<TrackPoint> trackPointList = DBDataCenter.getInstance().getTrackPointByWayTrail(wt, regions);
            int count = trackPointList.size();
            if (count < 2) {
                continue;
            }
            long B = SystemClock.uptimeMillis();

            int pathstyle = wt.getPathstyle();
            PathEffect pathEffect = null;

            if (wtOne != null) {
                pathstyle = 0;
            }
            switch (pathstyle) {
                default:
                case 0://实线
                    pathEffect = new DashPathEffect(new float[]{5, 0}, 0);
                    break;
                case 1://虚线1
                    pathEffect = new DashPathEffect(new float[]{5, 5, 5, 5}, 1);
                    break;
                case 2://虚线2
                    pathEffect = new DashPathEffect(new float[]{10, 10}, 1);
                    break;
                case 3://虚线2
                    pathEffect = new DashPathEffect(new float[]{20, 10, 5, 10}, 0);
                    break;
                case 4://虚线2
                    pathEffect = new DashPathEffect(new float[]{20, 10}, 0);
                    break;
                case 5://虚线2
                    pathEffect = new DashPathEffect(new float[]{12, 8, 6, 4}, 0);
                    break;
            }
            paint.setPathEffect(pathEffect);
            Path path = new Path();

            paint.setColor(wt.getColor());
            if (wtOne != null) {
                //当前导航的航迹
                paint.setColor(Color.parseColor("#AADD3833"));
            }
            Point ffA = null;
            for (int i = 0; i < count; i++) {
                TrackPoint tp = trackPointList.get(i);
                LonLat poiLL = tp.getLL();
                Point ffB = Start.getInstance().MapKit().LL2XY(poiLL);

                long C = SystemClock.uptimeMillis();
                //画线段,一段段判断+画--已预先判断范围
                if (i > 0) {
//                    canvas.drawLine(ffA.x * ws, ffA.y * ws, ffB.x * ws, ffB.y * ws, paint);
                    LonLat poiLLA = trackPointList.get(i - 1).getLL();
                    if (Math.abs(poiLLA.GetLon() - poiLL.GetLon()) > 0.03 || Math.abs(poiLLA.GetLat() - poiLL.GetLat()) > 0.03) {

                    } else {
                        int[] line = {ffA.x, ffA.y, ffB.x, ffB.y};
                        if (Utils.revisePt(line, w, h)) {
                            path.moveTo(line[0] * ws, line[1] * ws);
                            path.lineTo(line[2] * ws, line[3] * ws);
                        }
//                    path.moveTo(ffA.x * ws, ffA.y * ws);
//                    path.lineTo(ffB.x * ws, ffB.y * ws);
                    }
                }
                long D = SystemClock.uptimeMillis();
                //画圆点
//                if (isInMapRegion(poiLL)) {
//                    paint.setColor(Color.parseColor("#AAAABBAA"));
//                    Point e = Start.getInstance().MapKit().LL2XY(poiLL);
//                    canvas.drawCircle(e.x * ws, e.y * ws, 6, paint);
//                }
                ffA = ffB;
            }
            canvas.drawPath(path, paint);

            //-----单个航迹 画起点和终点
            if (wtOne != null && wtOne.trackPointList.size() > 2) {
                LonLat poiLLA = wtOne.trackPointList.get(0).getLL();

                Bitmap bmS = ((BitmapDrawable) context.getResources().getDrawable(
                        R.drawable.map_marker3)).getBitmap();
                Bitmap bmD = ((BitmapDrawable) context.getResources().getDrawable(
                        R.drawable.map_marker2)).getBitmap();
                if (isInMapRegion(poiLLA)) {
                    Bitmap bm = bmS;
                    if (wtOne.isReverse) {
                        bm = bmD;
                    }
                    ffA = Start.getInstance().MapKit().LL2XY(poiLLA);
                    int x = (int) (ffA.x * ws - bm.getWidth() / 2);
                    int y = (int) (ffA.y * ws - bm.getHeight());
                    canvas.drawBitmap(bm, x, y, null);
                }
                int size = wtOne.trackPointList.size();
                LonLat poiLLB = wtOne.trackPointList.get(size - 1).getLL();
                if (isInMapRegion(poiLLB)) {
                    Bitmap bm = bmD;
                    if (wtOne.isReverse) {
                        bm = bmS;
                    }
                    ffA = Start.getInstance().MapKit().LL2XY(poiLLB);
                    int x = (int) (ffA.x * ws - bm.getWidth() / 2);
                    int y = (int) (ffA.y * ws - bm.getHeight());
                    canvas.drawBitmap(bm, x, y, null);
                }
            }

            //------
            long E = SystemClock.uptimeMillis();

            Long x = E - A;
            Long x1 = B - A;
            Long x2 = E - B;
            Long x3 = A - Z;

            Long x4 = A - Z;

        }
    }

    //过滤屏幕内的点
    private ArrayList<TrackPoint> getTrackPointByWayTrail(WayTrail wt, double[] regions, int w) {
        if (wt == null || regions == null) {
            return null;
        }

        if (wt.trackPointList == null) {
            wt.trackPointList = DBDataCenter.getInstance().getTrackPointByWayTrail(wt, null);
        }

        if (wt.trackPointList == null) {
            return null;
        }

        //5像素经纬度的距离
        double minX = Math.abs(regions[0] - regions[2]) * 5 / w;

        int i = 0;
        int step = getStep(regions, w);

        double range = 0.01;
        double maxLon = regions[0] + range;
        double maxLat = regions[1] + range;
        double minLon = regions[2] - range;
        double minLat = regions[3] - range;
        ArrayList<TrackPoint> trackPointList = new ArrayList<TrackPoint>();
        int count = wt.trackPointList.size();
        if (count < 1) {
            return trackPointList;
        }

        long A = SystemClock.uptimeMillis();

        TrackPoint tp0 = wt.trackPointList.get(0);
        trackPointList.add(tp0);

        for (i = 1; i < count; i += step) {
            TrackPoint tp1 = wt.trackPointList.get(i);
            int size = trackPointList.size();
            tp0 = trackPointList.get(size - 1);

            // A->B 距离太近，跳过B
            if (Math.abs(tp0.getLL().GetLon() - tp1.getLL().GetLon()) + Math.abs(tp0.getLL().GetLat() - tp1.getLL().GetLat()) <= minX) {
                continue;
            }

            if (tp1.getLL().GetLon() > maxLon || tp1.getLL().GetLon() < minLon
                    || tp1.getLL().GetLat() > maxLat || tp1.getLL().GetLon() < minLat) {
                continue;
            }

    /*        //在同一外边，A->B, 去A，保留B
            if ( (tp0.getLL().GetLon() < minLon && tp1.getLL().GetLon() < minLon) ||
                    (tp0.getLL().GetLon() > maxLon && tp1.getLL().GetLon() > maxLon) ||
                    (tp0.getLL().GetLat() < minLat && tp1.getLL().GetLat() < minLat) ||
                    (tp0.getLL().GetLat() > maxLat && tp1.getLL().GetLat() > maxLat) ) {
                if (size > 0) {
                    trackPointList.remove(size - 1);
                }
            }

            //A->B, AB都远离，去A，保留B -- （原方案）
            if ((tp0.getLL().GetLon() > maxLon + 0.01 || tp0.getLL().GetLon() < minLon - 0.01
                    || tp0.getLL().GetLat() > maxLat + 0.01 || tp0.getLL().GetLon() < minLat - 0.01)
                    && (tp1.getLL().GetLon() > maxLon + 0.01 || tp1.getLL().GetLon() < minLon - 0.01
                    || tp1.getLL().GetLat() > maxLat + 0.01 || tp1.getLL().GetLon() < minLat - 0.01)) {
                continue;
            }
            */
            trackPointList.add(tp1);

        }

        //加最后一个点
        if (wt.trackPointList.size() > 0 && i > wt.trackPointList.size() - 1) {
            i = wt.trackPointList.size() - 1;
            TrackPoint tp = wt.trackPointList.get(i);
            if (tp.getLL().GetLon() > maxLon || tp.getLL().GetLon() < minLon
                    || tp.getLL().GetLat() > maxLat || tp.getLL().GetLon() < minLat) {
            } else {
                trackPointList.add(tp);
            }
        }

        long B = SystemClock.uptimeMillis() - A;

        int size = trackPointList.size();
        return trackPointList;
    }

    private boolean isInMapRegion(LonLat ll) {

        if (ll.GetLon() > _maxLon || ll.GetLat() > _maxLat
                || ll.GetLon() < _minLon || ll.GetLat() < _minLat) {
            return false;
        }

        return true;
    }

    //30米    150000
//50米    100000
//100米    50000
//200米    250000
//500米    10000
//1km    5000
//2km    2500
//5km   1000  --全上海
//10km   500
//20km   250
//50km   100
    //最大速度 车 30 米／秒

    //minX--5个像素的距离
    private int getStep(double[] regions, int w) {

        int step = 1;

        if (regions == null) {
            return step;
        }

        LonLat llA = new LonLat(regions[0], regions[1]);
        LonLat llB = new LonLat(regions[2], regions[1]);

        //屏幕x距离/w  320
        int minX = (int) (Start.getInstance().MapKit().getDistance(llA, llB) / w);

        if (minX <= 5) {
            step = 1;
        } else if (minX <= 6) {
            step = 2; //50米比例尺
        } else if (minX <= 7) {
            step = 3; //100米比例尺
        } else if (minX < 10) {
            step = 6; //200米比例尺
        } else if (minX < 15) {
            step = 16; //500米比例尺
        } else if (minX < 25) {
            step = 32;//1km
        } else if (minX < 45) {
            step = 70;//2km
        } else if (minX < 105) {
            step = 140;//5km
        } else if (minX < 200) {
            step = 300;//10km
        } else {
            step = 600;
        }

//        double scale = Start.getInstance().MapKit().getScale();
//        if (scale >= 100000) {
//            step = 1;//50米比例尺，1秒 1个点
//        } else if (scale >= 50000) {
//            step = 2;//100米比例尺，2秒 1个点
//        } else if (scale >= 250000) {
//            step = 3;
//        } else if (scale >= 10000) {
//            step = 10;
//        } else if (scale >= 5000) {
//            step = 20;
//        } else if (scale >= 2500) {
//            step = 50;
//        } else if (scale >= 1000) {
//            step = 100;
//        } else if (scale >= 500) {
//            step = 200;
//        } else if (scale >= 250) {
//            step = 400;
//        } else {
//            step = 1000;
//        }
        return step;
    }

//    public void drawWayTrail2(Context context, Canvas canvas, float ws, MapView mapView, WayTrail wtOne, boolean isgcj02) {
//        if (mapView == null) {
//            return;
//        }
//
//        BoundingBox bb = mapView.getBoundingBox();//获取当前区域
//        //double[] regions = {_maxLon, _maxLat, _minLon, _minLat};
//        double[] regions = {bb.getLonEast(), bb.getLatNorth(), bb.getLonWest(), bb.getLatSouth()};
//
//        _maxLon = regions[0];
//        _maxLat = regions[1];
//        _minLon = regions[2];
//        _minLat = regions[3];
//
//        int w = mapView.getWidth();
//        int h = mapView.getHeight();
//
//        long Z = SystemClock.uptimeMillis();
//
//        //显示所有航迹 --最新的航迹最后画（包括当前航迹）
//        ArrayList<WayTrail> wayTrailList = DBDataCenter.getInstance().getWaytrailListByOrder(0);
//
//        Paint paint = new Paint();
//        paint.setStyle(Paint.Style.STROKE);
//        paint.setStrokeWidth(8);
//        paint.setAntiAlias(true);
//
//        for (WayTrail wt : wayTrailList) {
//            if (wtOne != null && wtOne.getId() != wt.getId()) {
//                continue;
//            }
//
//            if (wtOne == null && !wt.getIsshow()) {
//                continue;
//            }
//            long A = SystemClock.uptimeMillis();
//            // 每次查询数据库慢，还是放内存里试试
//            ArrayList<TrackPoint> trackPointList = getTrackPointByWayTrail(wt, regions, w);
//            if (trackPointList == null) {
//                continue;
//            }
////            ArrayList<TrackPoint> trackPointList = DBDataCenter.getInstance().getTrackPointByWayTrail(wt, regions);
//            int count = trackPointList.size();
//            if (count < 2) {
//                continue;
//            }
//            long B = SystemClock.uptimeMillis();
//
//            int pathstyle = wt.getPathstyle();
//            PathEffect pathEffect = null;
//
//            if (wtOne != null) {
//                pathstyle = 0;
//            }
//            switch (pathstyle) {
//                default:
//                case 0://实线
//                    pathEffect = new DashPathEffect(new float[]{5, 0}, 0);
//                    break;
//                case 1://虚线1
//                    pathEffect = new DashPathEffect(new float[]{5, 5, 5, 5}, 1);
//                    break;
//                case 2://虚线2
//                    pathEffect = new DashPathEffect(new float[]{10, 10}, 1);
//                    break;
//                case 3://虚线2
//                    pathEffect = new DashPathEffect(new float[]{20, 10, 5, 10}, 0);
//                    break;
//                case 4://虚线2
//                    pathEffect = new DashPathEffect(new float[]{20, 10}, 0);
//                    break;
//                case 5://虚线2
//                    pathEffect = new DashPathEffect(new float[]{12, 8, 6, 4}, 0);
//                    break;
//            }
//            paint.setPathEffect(pathEffect);
//            Path path = new Path();
//
//            paint.setColor(wt.getColor());
//            if (wtOne != null) {
//                //当前航迹
//                paint.setColor(Color.parseColor("#AADD3833"));
//            }
//            Point ffA = null;
//            LonLat poiLLA = null;
//            for (int i = 0; i < count; i++) {
//                TrackPoint tp = trackPointList.get(i);
//                LonLat poiLL = tp.getLL();
//
//                if (!isgcj02) {
//                    poiLL = Utils.gcj02towgs84(poiLL.GetLon(), poiLL.GetLat());//Utils 火星坐标 to GPS
//                }
//
//                Point ffB = LL2XY(poiLL, mapView);
//
//                long C = SystemClock.uptimeMillis();
//                //画线段,一段段判断+画--已预先判断范围
//                if (i > 0) {
////                    canvas.drawLine(ffA.x * ws, ffA.y * ws, ffB.x * ws, ffB.y * ws, paint);
//                    if (Math.abs(poiLLA.GetLon() - poiLL.GetLon()) > 0.03 || Math.abs(poiLLA.GetLat() - poiLL.GetLat()) > 0.03) {
//
//                    } else {
//                        int[] line = {ffA.x, ffA.y, ffB.x, ffB.y};
//                        if (Utils.revisePt(line, w, h)) {
//                            path.moveTo(line[0], line[1]);
//                            path.lineTo(line[2], line[3]);
//                        }
////                    path.moveTo(ffA.x * ws, ffA.y * ws);
////                    path.lineTo(ffB.x * ws, ffB.y * ws);
//                    }
//                }
//                long D = SystemClock.uptimeMillis();
//                //画圆点
////                if (isInMapRegion(poiLL)) {
////                    paint.setColor(Color.parseColor("#AAAABBAA"));
////                    Point e = Start.getInstance().MapKit().LL2XY(poiLL);
////                    canvas.drawCircle(e.x * ws, e.y * ws, 6, paint);
////                }
//                ffA = ffB;
//                poiLLA = poiLL;
//            }
//            canvas.drawPath(path, paint);
//
//            //-----单个航迹 画起点和终点
//            if (wtOne != null && wtOne.trackPointList.size() > 2) {
//                poiLLA = wtOne.trackPointList.get(0).getLL();
//
//                if (!isgcj02) {
//                    poiLLA = Utils.gcj02towgs84(poiLLA.GetLon(), poiLLA.GetLat());//Utils 火星坐标 to GPS
//                }
//
//                Bitmap bmS = ((BitmapDrawable) context.getResources().getDrawable(
//                        R.drawable.map_marker3)).getBitmap();
//                Bitmap bmD = ((BitmapDrawable) context.getResources().getDrawable(
//                        R.drawable.map_marker2)).getBitmap();
//                if (isInMapRegion(poiLLA)) {
//                    Bitmap bm = bmS;
//                    if (wtOne.isReverse) {
//                        bm = bmD;
//                    }
//                    ffA = LL2XY(poiLLA, mapView);
//                    int x = (int) (ffA.x - bm.getWidth() / 2);
//                    int y = (int) (ffA.y - bm.getHeight());
//                    canvas.drawBitmap(bm, x, y, null);
//                }
//                int size = wtOne.trackPointList.size();
//                LonLat poiLLB = wtOne.trackPointList.get(size - 1).getLL();
//                if (!isgcj02) {
//                    poiLLB = Utils.gcj02towgs84(poiLLB.GetLon(), poiLLB.GetLat());//Utils 火星坐标 to GPS
//                }
//
//                if (isInMapRegion(poiLLB)) {
//                    Bitmap bm = bmD;
//                    if (wtOne.isReverse) {
//                        bm = bmS;
//                    }
//                    ffA = LL2XY(poiLLB, mapView);
//                    int x = (int) (ffA.x - bm.getWidth() / 2);
//                    int y = (int) (ffA.y - bm.getHeight());
//                    canvas.drawBitmap(bm, x, y, null);
//                }
//            }
//
//            //------
//            long E = SystemClock.uptimeMillis();
//
//            Long x = E - A;
//            Long x1 = B - A;
//            Long x2 = E - B;
//            Long x3 = A - Z;
//
//            Long x4 = A - Z;
//
//        }
//    }
//
//    Point LL2XY(LonLat ll, MapView mapView) {
//        Point A = new Point();
//        Point B = new Point();
//        mapView.getProjection().toProjectedPixels(ll.GetLat(),
//                ll.GetLon(), A);
//        Projection pj = mapView.getProjection();
//        pj.toPixelsFromProjected(A, B);
//        return B;
//    }
//
//
//    public void drawWayTrail3(Context context, org.mapsforge.core.graphics.Canvas canvas, org.mapsforge.core.model.BoundingBox bb, byte zoomLevel, org.mapsforge.core.model.Point topLeftPoint, DisplayModel displayModel, WayTrail wtOne) {
//
//        int w = canvas.getWidth();
//        int h = canvas.getHeight();
//
//        double[] regions = {bb.maxLongitude, bb.maxLatitude, bb.minLongitude, bb.minLatitude};
//
//        android.graphics.Canvas androidCanvas = AndroidGraphicFactory.getCanvas(canvas);
//
//        _maxLon = regions[0];
//        _maxLat = regions[1];
//        _minLon = regions[2];
//        _minLat = regions[3];
//
//        long Z = SystemClock.uptimeMillis();
//
//        //显示所有航迹 --最新的航迹最后画（包括当前航迹）
//        ArrayList<WayTrail> wayTrailList = DBDataCenter.getInstance().getWaytrailListByOrder(0);
//
//        Paint paint = new Paint();
//        paint.setStyle(Paint.Style.STROKE);
//        paint.setStrokeWidth(8);
//        paint.setAntiAlias(true);
//
//        long mapSize = MercatorProjection.getMapSize(zoomLevel, displayModel.getTileSize());
//        Paint paintZ = new Paint();
//
//        for (WayTrail wt : wayTrailList) {
//            if (wtOne != null && wtOne.getId() != wt.getId()) {
//                continue;
//            }
//
//            if (wtOne == null && !wt.getIsshow()) {
//                continue;
//            }
//            long A = SystemClock.uptimeMillis();
//            // 每次查询数据库慢，还是放内存里试试
//            ArrayList<TrackPoint> trackPointList = getTrackPointByWayTrail(wt, regions, w);
//            if (trackPointList == null) {
//                continue;
//            }
////            ArrayList<TrackPoint> trackPointList = DBDataCenter.getInstance().getTrackPointByWayTrail(wt, regions);
//            int count = trackPointList.size();
//            if (count < 2) {
//                continue;
//            }
//            long B = SystemClock.uptimeMillis();
//
//            int pathstyle = wt.getPathstyle();
//            if (wtOne != null) {
//                pathstyle = 0;
//            }
//            PathEffect pathEffect = null;
//            switch (pathstyle) {
//                default:
//                case 0://实线
//                    pathEffect = new DashPathEffect(new float[]{5, 0}, 0);
//                    break;
//                case 1://虚线1
//                    pathEffect = new DashPathEffect(new float[]{5, 5, 5, 5}, 1);
//                    break;
//                case 2://虚线2
//                    pathEffect = new DashPathEffect(new float[]{10, 10}, 1);
//                    break;
//                case 3://虚线2
//                    pathEffect = new DashPathEffect(new float[]{20, 10, 5, 10}, 0);
//                    break;
//                case 4://虚线2
//                    pathEffect = new DashPathEffect(new float[]{20, 10}, 0);
//                    break;
//                case 5://虚线2
//                    pathEffect = new DashPathEffect(new float[]{12, 8, 6, 4}, 0);
//                    break;
//            }
//            paint.setPathEffect(pathEffect);
//            Path path = new Path();
//
//            paint.setColor(wt.getColor());
//            if (wtOne != null) {
//                //当前航迹
//                paint.setColor(Color.parseColor("#AADD3833"));
//            }
//            Point ffA = null;
//            LonLat poiLLA = null;
//            for (int i = 0; i < count; i++) {
//                TrackPoint tp = trackPointList.get(i);
//                LonLat poiLL = tp.getLL();
//                poiLL = Utils.gcj02towgs84(poiLL.GetLon(), poiLL.GetLat());//Utils 火星坐标 to GPS
//                int x = (int)(MercatorProjection.longitudeToPixelX(poiLL.GetLon(), mapSize) - topLeftPoint.x);
//                int y = (int)(MercatorProjection.latitudeToPixelY(poiLL.GetLat(), mapSize) - topLeftPoint.y);
//                Point ffB = new Point(x, y);
//
//                long C = SystemClock.uptimeMillis();
//                //画线段,一段段判断+画--已预先判断范围
//                if (i > 0) {
////                    canvas.drawLine(ffA.x * ws, ffA.y * ws, ffB.x * ws, ffB.y * ws, paint);
//                    if (Math.abs(poiLLA.GetLon() - poiLL.GetLon()) > 0.03 || Math.abs(poiLLA.GetLat() - poiLL.GetLat()) > 0.03) {
//
//                    } else {
//                        int[] line = {ffA.x, ffA.y, ffB.x, ffB.y};
//                        if (Utils.revisePt(line, w, h)) {
//                            path.moveTo(line[0], line[1]);
//                            path.lineTo(line[2], line[3]);
//                        }
////                    path.moveTo(ffA.x * ws, ffA.y * ws);
////                    path.lineTo(ffB.x * ws, ffB.y * ws);
//                    }
//                }
//                long D = SystemClock.uptimeMillis();
//                //画圆点
////                if (isInMapRegion(poiLL)) {
////                    paint.setColor(Color.parseColor("#AAAABBAA"));
////                    Point e = Start.getInstance().MapKit().LL2XY(poiLL);
////                    canvas.drawCircle(e.x * ws, e.y * ws, 6, paint);
////                }
//                ffA = ffB;
//                poiLLA = poiLL;
//            }
//            androidCanvas.drawPath(path, paint);
//
//            //-----单个航迹 画起点和终点
//            if (wtOne != null && wtOne.trackPointList.size() > 2) {
//                poiLLA = wtOne.trackPointList.get(0).getLL();
//                poiLLA = Utils.gcj02towgs84(poiLLA.GetLon(), poiLLA.GetLat());//Utils 火星坐标 to GPS
//                Bitmap bmS = ((BitmapDrawable) context.getResources().getDrawable(
//                        R.drawable.map_marker3)).getBitmap();
//                Bitmap bmD = ((BitmapDrawable) context.getResources().getDrawable(
//                        R.drawable.map_marker2)).getBitmap();
//
//                if (isInMapRegion(poiLLA)) {
//                    Bitmap bm = bmS;
//                    if (wtOne.isReverse) {
//                        bm = bmD;
//                    }
//
//                    int x = (int)(MercatorProjection.longitudeToPixelX(poiLLA.GetLon(), mapSize) - topLeftPoint.x);
//                    int y = (int)(MercatorProjection.latitudeToPixelY(poiLLA.GetLat(), mapSize) - topLeftPoint.y);
//                    ffA = new Point(x, y);
//
//                    x = (int) (ffA.x - bm.getWidth() / 2);
//                    y = (int) (ffA.y - bm.getHeight());
//                    androidCanvas.drawBitmap(bm, x, y, null);
//
//                }
//                int size = wtOne.trackPointList.size();
//                LonLat poiLLB = wtOne.trackPointList.get(size - 1).getLL();
//                poiLLB = Utils.gcj02towgs84(poiLLB.GetLon(), poiLLB.GetLat());//Utils 火星坐标 to GPS
//                if (isInMapRegion(poiLLB)) {
//                    Bitmap bm = bmD;
//                    if (wtOne.isReverse) {
//                        bm = bmS;
//                    }
//                    int x = (int)(MercatorProjection.longitudeToPixelX(poiLLB.GetLon(), mapSize) - topLeftPoint.x);
//                    int y = (int)(MercatorProjection.latitudeToPixelY(poiLLB.GetLat(), mapSize) - topLeftPoint.y);
//                    ffA = new Point(x, y);
//                    x = (int) (ffA.x - bm.getWidth() / 2);
//                    y = (int) (ffA.y - bm.getHeight());
//                    androidCanvas.drawBitmap(bm, x, y, null);
//                }
//            }
//
//            //------
//            long E = SystemClock.uptimeMillis();
//
//            Long x = E - A;
//            Long x1 = B - A;
//            Long x2 = E - B;
//            Long x3 = A - Z;
//
//            Long x4 = A - Z;
//
//        }
//    }

}
